package com.whiteape.book.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.whiteape.book.R;
import com.whiteape.book.common.WaConstants;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.model.bo.TypefaceBo;
import com.whiteape.book.model.type.LoadFileType;
import com.whiteape.book.net.RetrofitHelper;
import com.whiteape.book.ui.adapter.TypefaceManageAdapter;
import com.whiteape.book.ui.base.BaseActivity;
import com.whiteape.book.utils.FileUtils;
import com.whiteape.book.utils.JumpPermissionManagement;
import com.whiteape.book.utils.LogUtils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.ToastUtils;
import com.whiteape.book.utils.URLUtils;
import com.whiteape.book.utils.ZipUtils;
import com.whiteape.book.utils.ZipUtils2;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.progressmanager.ProgressListener;
import me.jessyan.progressmanager.ProgressManager;
import me.jessyan.progressmanager.body.ProgressInfo;

public class TypefaceManagerActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.lv_typeface)
    ListView listView;

    @BindView(R.id.tv_scan_local)
    TextView tvScan;

    TypefaceManageAdapter mAdapter;

    List<TypefaceBo> mData = new ArrayList<>();

    private final String[] typefaceNameArr = {"系统默认", "方正楷体", "汉仪贤二体免费版", "郑庆科黄油体", "站酷高端黑体", "站酷快乐体", "手写体"};
    private final String[] typefaceSizeArr = {"    ", "6.8M", "6.7M", "3.8M", "2.1M", "2.8M", "1.5M"};
    private final String[] typefaceUrlArr = {"",
            "http://js.xiazaicc.com/down/fangzhengkaitigbk_downcc.zip",
            "http://js.xiazaicc.com/down2/hyxet_downcc.zip",
            "http://js.xiazaicc.com/down2/zkqkhyt_downcc.zip",
            "http://js.xiazaicc.com/down1/zhankugaoduanhei_downcc.zip",
            "http://js.xiazaicc.com/down1/zhankukuaileti_downcc.zip",
            "http://js.xiazaicc.com/down1/yiqishouxieti_downcc.zip"
    };

    @Override
    protected int getContentId() {
        return R.layout.activity_typeface_manager;
    }

    private String getTypefaceFilePath(String name) {
        return WaConstants.FONT_CACHE_PATH + name + ".ttf";
    }

    private String getTypefaceZipFilePath(String name) {
        return WaConstants.FONT_CACHE_PATH + name + ".zip";
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        String currentTypeface = ReadSettingManager.getInstance().getTypeface();
        for (int i = 0; i < typefaceNameArr.length; i++) {
            TypefaceBo typefaceBo = new TypefaceBo();
            typefaceBo.setName(typefaceNameArr[i]);
            typefaceBo.setSize(typefaceSizeArr[i]);
            if (i == 0) {
                if (StringUtils.isEmpty(currentTypeface)) {
                    typefaceBo.setStateType(TypefaceBo.STATE_TYPE_USING);
                } else {
                    typefaceBo.setStateType(TypefaceBo.STATE_TYPE_DOWNLOADED);
                }
            } else {
                if (currentTypeface.equals(getTypefaceFilePath(typefaceNameArr[i]))) {
                    //
                    typefaceBo.setStateType(TypefaceBo.STATE_TYPE_USING);
                } else {
                    typefaceBo.setStateType(MediaStorageManager.isFontCached(typefaceNameArr[i]) ?
                            TypefaceBo.STATE_TYPE_DOWNLOADED : TypefaceBo.STATE_TYPE_UNDOWNLOADED);
                }
            }

            typefaceBo.setUrl(typefaceUrlArr[i]);
            mData.add(typefaceBo);
        }

    }

    @Override
    protected void initView() {
        super.initView();
        mAdapter = new TypefaceManageAdapter();
        listView.setAdapter(mAdapter);
        mAdapter.addItems(mData);
        mAdapter.notifyDataSetChanged();
    }

    private void checkPermissionAndSelectFile() {

        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.wa_common_tip)
                    .setMessage(R.string.permission_request_sdcard)
                    .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                        dialogInterface.dismiss();
                        rxPermissionRequest(rxPermissions);
                    }))
                    .setNegativeButton(R.string.wa_common_cancel, ((dialogInterface, i) -> {
                        dialogInterface.dismiss();
                        ToastUtils.show("已经拒绝权限，需要重新打开授权才可以扫描本地字体文件");
                        setResult(RESULT_CANCELED);
                        finish();
                    })).show();
        } else {

            scanFile();
        }
    }

    private void rxPermissionRequest(RxPermissions rxPermissions) {
        String permissionRequired = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        addDisposable(rxPermissions.requestEach(permissionRequired)
                .subscribe(permission -> {
                    if (permission.granted) {
                        // `permission.name` is granted !
                        scanFile();

                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
                        setResult(Activity.RESULT_CANCELED);
                        finish();
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                        new AlertDialog.Builder(this)
                                .setTitle(R.string.wa_common_tip)
                                .setMessage(R.string.permission_request_sdcard_goto_setting)
                                .setPositiveButton(R.string.wa_common_sure, ((dialogInterface, i) -> {
                                    //goto setting
                                    dialogInterface.dismiss();
                                    JumpPermissionManagement.goToSetting(this);
                                    setResult(RESULT_CANCELED);
                                    finish();

                                }))
                                .setNegativeButton(R.string.wa_common_cancel, ((dialogInterface, i) -> {
                                    dialogInterface.dismiss();
                                    ToastUtils.show("已拒绝权限，无法继续进行");
                                    setResult(RESULT_CANCELED);
                                    finish();
                                })).show();

                    }
                }));

    }

    private void scanFile() {
        Intent intent = new Intent(this, FileSystemActivity.class);
        intent.putExtra(FileSystemActivity.FILE_TYPE_KEY, LoadFileType.FILE_TYPE_TYPEFACE);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, LoadFileType.FILE_TYPE_TYPEFACE);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        tvScan.setOnClickListener(view -> {
            checkPermissionAndSelectFile();

        });
        mAdapter.setListener(this);

        listView.setOnItemClickListener(((adapterView, view, i, l) -> {

        }));
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("字体管理");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            LogUtils.e("TypefaceManagerActivity onActivityResult ,resultCode not ok, is " + resultCode);
            return;
        }
        if (requestCode == LoadFileType.FILE_TYPE_TYPEFACE) {
            List<File> fileList = (List<File>) data.getSerializableExtra("data");
            if(fileList == null) {
                finish();
                return;
            }
            File ttfFile = fileList.get(fileList.size() - 1);
            String path = ttfFile.getAbsolutePath();
            setResult(RESULT_OK, new Intent().putExtra("data", path));
            finish();

        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.typeface_tv_action || view.getId() == R.id.rl_typeface_item) {
            int position = (Integer) view.getTag();
            TypefaceBo typefaceBo = mData.get(position);
            if (typefaceBo.getStateType() == TypefaceBo.STATE_TYPE_DOWNLOADED) {
                //已下载的，直接使用
                if (position == 0) {
                    setResult(RESULT_OK, new Intent().putExtra("data", ""));
                } else {
                    setResult(RESULT_OK, new Intent().putExtra("data", getTypefaceFilePath(typefaceNameArr[position])));
                }
                finish();
            } else if (typefaceBo.getStateType() == TypefaceBo.STATE_TYPE_UNDOWNLOADED) {
                //开始下载
                download(position);
            }
        }
    }

    private void download(int position) {

        String url = typefaceUrlArr[position];
        ProgressManager.getInstance().addResponseListener(url, new TypefaceProgressListener(position));
        try {
            addDisposable(RetrofitHelper.getInstance().getHttpApiImpl(URLUtils.getBaseUrl(url))
                    .downloadByRx(url)
                    .subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.io())
                    .subscribe(responseBody -> {
                        FileUtils.saveFile(responseBody.byteStream(), getTypefaceZipFilePath(typefaceNameArr[position]));
                    }, Throwable::printStackTrace));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    class TypefaceProgressListener implements ProgressListener {
        int position;
        DecimalFormat decimalFormat = new DecimalFormat("0.00");

        TypefaceProgressListener(int position) {
            this.position = position;
        }

        @Override
        public void onProgress(ProgressInfo progressInfo) {
            if (progressInfo.isFinish()) {
                mData.get(position).setSize(typefaceSizeArr[position]);
                mData.get(position).setStateType(TypefaceBo.STATE_TYPE_USING);
                for (int i = 0; i < mData.size(); i++) {
                    if (i != position) {
                        mData.get(position).setStateType(MediaStorageManager.isFontCached(typefaceNameArr[i]) ?
                                TypefaceBo.STATE_TYPE_DOWNLOADED : TypefaceBo.STATE_TYPE_UNDOWNLOADED);
                    }
                }
                ReadSettingManager.getInstance().setTypeface(getTypefaceFilePath(typefaceNameArr[position]));
                mAdapter.notifyDataSetChanged();
                //解压
                try {
                    ZipUtils.unzipFileWithSuffix(getTypefaceZipFilePath(typefaceNameArr[position]), WaConstants.FONT_CACHE_PATH, ".ttf", typefaceNameArr[position]);
//                    List<File> fileList = ZipUtils2.getFileList(getTypefaceZipFilePath(typefaceNameArr[position]), false, true);
//                    for (File file : fileList) {
//                        System.out.println(file.getAbsolutePath());
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                setResult(RESULT_OK, new Intent().putExtra("data", getTypefaceFilePath(typefaceNameArr[position])));
                finish();
                return;
            }

            String currentTotal = typefaceSizeArr[position];
            float total = Float.parseFloat(currentTotal.substring(0, currentTotal.length() - 1));
            long downloadedBytes = progressInfo.getCurrentbytes();
            float kiloBytes = downloadedBytes / 1024.0f;
            if (kiloBytes > 1) {
                float megaBytes = kiloBytes / 1024.0f;
                String mega = decimalFormat.format(megaBytes);
                mData.get(position).setSize(mega + "M/" + currentTotal);
                if (megaBytes >= total) {
                    mData.get(position).setSize(total + "M/" + currentTotal);
                }
            } else {
                String kilo = decimalFormat.format(kiloBytes);
                mData.get(position).setSize(kilo + "K/" + currentTotal);
            }
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public void onError(long id, Exception e) {

        }
    }


}

